package com.outsourcing.bottle.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;

import com.outsourcing.bottle.domain.FriendLevelEntry;

/**
 * 瓶友等级表
 * @author 06peng
 *
 */
public class FriendLevelTable {

	private final String TABLE_FRIENDLEVEL = "friend_level";
	private DBManagerImpl db = null;
	public FriendLevelTable() {
		if (db == null) {
			db = DBManager.get();
		}
		if (!db.isTableExits(db.getConnection(), TABLE_FRIENDLEVEL)) {
			createFriendLevel();
		}
	}
	
	private void createFriendLevel() {
		String createSql = "create table if not exists " + TABLE_FRIENDLEVEL
				+ " (id integer  primary key autoincrement, flevel_id integer, flevel_name_cn varchar, " +
						"flevel_name_en varchar, flevel_level integer, flevel_credit integer, flevel_ttcredit integer, " +
						"flevel_cron varchar)";
		db.creatTable(db.getConnection(), createSql, TABLE_FRIENDLEVEL);
	}
	
	public ArrayList<FriendLevelEntry> getFriendLevels() {
		Cursor cursor = null;
		ArrayList<FriendLevelEntry> friendLevels = null;
		try {
			cursor = db.find(db.getConnection(), "select * from " + TABLE_FRIENDLEVEL, null);
			if (cursor != null) {
				friendLevels = new ArrayList<FriendLevelEntry>();
				while (cursor.moveToNext()) {
					FriendLevelEntry friendLevel = new FriendLevelEntry();
					friendLevel.setFlevel_id(cursor.getInt(cursor.getColumnIndex("flevel_id")));
					friendLevel.setFlevel_level(cursor.getInt(cursor.getColumnIndex("flevel_level")));
					friendLevel.setFlevel_credit(cursor.getInt(cursor.getColumnIndex("flevel_credit")));
					friendLevel.setFlevel_ttcredit(cursor.getInt(cursor.getColumnIndex("flevel_ttcredit")));
					friendLevel.setFlevel_cron(cursor.getString(cursor.getColumnIndex("flevel_cron")));
					friendLevel.setFlevel_name_cn(cursor.getString(cursor.getColumnIndex("flevel_name_cn")));
					friendLevel.setFlevel_name_en(cursor.getString(cursor.getColumnIndex("flevel_name_en")));
					friendLevels.add(friendLevel);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return friendLevels;
	}
	
	public void saveFriendLevel(FriendLevelEntry friendLevel) {
		ContentValues values = new ContentValues();
		values.put("flevel_id", friendLevel.getFlevel_id());
		values.put("flevel_name_cn", friendLevel.getFlevel_name_cn());
		values.put("flevel_name_en", friendLevel.getFlevel_name_en());
		values.put("flevel_level", friendLevel.getFlevel_level());
		values.put("flevel_credit", friendLevel.getFlevel_credit());
		values.put("flevel_ttcredit", friendLevel.getFlevel_ttcredit());
		values.put("flevel_cron", friendLevel.getFlevel_cron());
		db.save(db.getConnection(), TABLE_FRIENDLEVEL, values);
	}
	
	public void clearTable() {
		db.delete(db.getConnection(), TABLE_FRIENDLEVEL, null, null);
	}
}
